import React from 'react';
import { useState, useEffect } from 'react'
import type { FC } from 'react';
import { Image, Input, Button, Toast } from 'antd-mobile'
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import './index.css'

// 导入图标
import emailIcon from '../../../public/Icon/email.png'
import passIcon from '../../../public/Icon/password.png'
import loginHand from '../../../public/Image/login_hand.png'
import invitationIcon from '../../../public/Icon/invitation_code.png'
import request from '../../api/axios'
import { encrypt } from '../../utils/encrypt';
import { useNavigate } from 'react-router-dom';
const Register: FC = ({ }) => {
    const navigate = useNavigate();
    const [email, setEmail] = useState("");
    const [verifyCode, setVerifyCode] = useState("");
    const [password, setPassword] = useState("");
    const [confirmPassword, setConfirmPassword] = useState("");
    const [invitationCode, setInvitationCode] = useState("");
    const [visible, setVisible] = useState(false);
    const [visibleConfirm, setVisibleConfirm] = useState(false);
    const [countdown, setCountdown] = useState(0);
    const [isGettingCode, setIsGettingCode] = useState(false);

    // 倒计时效果
    useEffect(() => {
        let timer: number;
        if (countdown > 0) {
            timer = window.setTimeout(() => {
                setCountdown(countdown - 1);
            }, 1000);
        } else {
            // 倒计时结束，重置状态
            setIsGettingCode(false);
        }
        return () => {
            if (timer) clearTimeout(timer);
        };
    }, [countdown]);


    const handleGetVerifyCode = async () => {
        // 邮箱验证
        if (!email.trim()) {
            Toast.show('请输入邮箱');
            return;
        }

        // 邮箱格式验证
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            Toast.show('请输入正确的邮箱格式');
            return;
        }

        // 如果正在倒计时，不允许重复点击
        if (countdown > 0) {
            return;
        }

        try {
            setIsGettingCode(true);
            setCountdown(60); // 设置60秒倒计时

            const response = await request.post(`/api/health/user/v1/sendOutEmailCode?email=${email}`);

            if (response && response.data?.status === '9999') {
                // Toast.show('验证码已发送，请查收邮箱');
                // 成功时保持倒计时继续
            } else {
                // Toast.show(response?.data?.message || '验证码发送失败，请重试');
                // 失败时也保持倒计时，防止频繁请求
            }
        } catch (error) {
            console.error('发送验证码失败', error);
            // Toast.show('网络错误，请稍后重试');
            // 网络错误时也保持倒计时，防止频繁请求
        }
    }

    const handleRegister = () => {
        if (password === confirmPassword) {
            let data = {
                email: email,
                code: verifyCode,
                pwd1: encrypt(password),
                pwd2: encrypt(confirmPassword),
                invitationCode: invitationCode
            }
            let url = `/api/health/user/v1/register?email=${email}&code=${verifyCode}&pwd1=${encrypt(password)}&pwd2=${encrypt(confirmPassword)}`
            if (invitationCode) {
                url += `&invitationCode=${invitationCode}`
            }
            // console.log('注册', { email, verifyCode, password, confirmPassword, invitationCode });
            request.post(url, { params: data }).then(() => {
                navigate('/login');
            })
        }
        // TODO: 实现注册逻辑

    }

    return (
        <div className="register-page">
            {/* 顶部图标 */}
            <div className="register-top-icon">
                <div className="icon-circle">
                    <Image src={loginHand} />
                </div>
            </div>

            {/* 白色注册卡片 */}
            <div className="register-card">
                {/* 邮箱输入框和获取验证码按钮 */}
                <div className="input-group-with-button">
                    <div className="input-icon">
                        <Image src={emailIcon} width="20px" height="20px" />
                    </div>
                    <div className="input-wrapper">
                        <Input
                            placeholder='请输入邮箱'
                            className="register-input"
                            value={email}
                            onChange={setEmail}
                        />
                    </div>
                    <div className="verify-button-wrapper">
                        <Button
                            color='primary'
                            fill='solid'
                            size="small"
                            className="verify-button"
                            onClick={handleGetVerifyCode}
                            disabled={countdown > 0 || isGettingCode}
                        >
                            {countdown > 0 ? `${countdown}秒后重新获取` : '获取验证码'}
                        </Button>
                    </div>
                </div>

                {/* 验证码输入框 */}
                <div className="input-group">
                    <div className="input-icon">
                        <div className="verify-icon">✓</div>
                    </div>
                    <Input
                        placeholder='请输入验证码'
                        className="register-input"
                        value={verifyCode}
                        onChange={setVerifyCode}
                    />
                </div>

                {/* 密码输入框 */}
                <div className="input-group">
                    <div className="input-icon">
                        <Image src={passIcon} width="20px" height="20px" />
                    </div>
                    <Input
                        type={visible ? 'text' : 'password'}
                        placeholder='请输入密码'
                        className="register-input"
                        value={password}
                        onChange={setPassword}
                    />
                    <div className="password-toggle" onClick={() => setVisible(!visible)}>
                        {!visible ? (
                            <EyeInvisibleOutline fontSize={20} />
                        ) : (
                            <EyeOutline fontSize={20} />
                        )}
                    </div>
                </div>

                {/* 确认密码输入框 */}
                <div className="input-group">
                    <div className="input-icon">
                        <Image src={passIcon} width="20px" height="20px" />
                    </div>
                    <Input
                        type={visibleConfirm ? 'text' : 'password'}
                        placeholder='请再次输入密码'
                        className="register-input"
                        value={confirmPassword}
                        onChange={setConfirmPassword}
                    />
                    <div className="password-toggle" onClick={() => setVisibleConfirm(!visibleConfirm)}>
                        {!visibleConfirm ? (
                            <EyeInvisibleOutline fontSize={20} />
                        ) : (
                            <EyeOutline fontSize={20} />
                        )}
                    </div>
                </div>

                {/* 邀请码输入框 */}
                <div className="input-group last-input">
                    <div className="input-icon">
                        <Image src={invitationIcon} width="20px" height="20px" />
                    </div>
                    <Input
                        placeholder='请输入邀请码'
                        className="register-input"
                        value={invitationCode}
                        onChange={setInvitationCode}
                    />
                    <div className="optional-text">选填</div>
                </div>
            </div>

            {/* 注册按钮 */}
            <div className="register-button-container">
                <Button
                    block
                    size='large'
                    className="register-button"
                    onClick={handleRegister}
                >
                    注册
                </Button>
            </div>
        </div>
    );
};

export default Register;